import { SET_SHIPPING, SET_PAYMENT } from '../constants/cart'
import { typeAddress, typePayment } from '../types/cart'
import { Cart } from './types'
interface Action {
  type: string,
  address: typeAddress,
  payment: typePayment,
  error?: string
}

export const cartReducer = (state:Cart, action:Action):Cart => {
  switch (action.type) {
    case SET_SHIPPING: // 设置收货地址
      const address:typeAddress = action.address

      return address
        ? {
          ...state,
          address
        }
        : state
    case SET_PAYMENT: // 设置支付方式
      const payment:typePayment = action.payment

      return payment
        ? {
          ...state,
          payment
        }
        : state
    default:
      return { ...state }
  }
}

export const setShipping = (data:typeAddress) => async(dispatch:any) => {
  dispatch({
    type: SET_SHIPPING,
    address: data
  })
  localStorage.setItem('address', JSON.stringify(data))
}

export const setPaymentStore = (data:typePayment) => async(dispatch:any) => {
  dispatch({
    type: SET_PAYMENT,
    payment: data
  })
}
